import { Table, Button, Tooltip, Popconfirm, message } from 'antd';  
import { DeleteOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import axios from 'axios'



const App = () => {

  // 定义了 data loading pagination
  const [data, setData] = useState();
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 3
  });

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);


  // 定义了一个函数   fetchData
  // 获取数据设置了分页
  const fetchData = (params = {}) => {
    setLoading(true);
    axios.get(`/api/list?current=${params.current}&pagesize=${params.pageSize}`).then(data => {
      setData(data.data.data)
      setLoading(false);
      setPagination({
        ...params,
        total: data.data.total
      })
    })
  };

  // 表格的列的结构
  const columns = [
    {
      title: 'id',
      dataIndex: '_id',
    },
    {
      title: '商品名称',
      dataIndex: 'title',

      render: (name) => `${name}`,
    },
    {
      title: '商品价格',
      dataIndex: 'price',
    },
    {
      title: '商品主图',
      dataIndex: 'mainImage',
      render: (text)=>{
        return <img  width='100' src={text} alt='true'/>
      }
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
    },
    {
      title: '操作',
      dataIndex: 'setting',
      render: (text,data)=>{
        return (
          <Popconfirm
          title="你确定要删除吗？"
          onConfirm={()=>{
            axios.post('/api/goodsDel', {
              _id: data._id
            }).then(({data}) => {
              if (data.code == 200) {
                message.info('删除成功')
                fetchData(pagination)
              }
            })
          }}
          onCancel={()=>{}}
          okText="删除"
          cancelText="取消"
        >
          <Button danger shape="circle" icon={<DeleteOutlined />} />
        </Popconfirm>
        )
      }
    }
  ];

  


  // 一进入界面  调用  fetchData 函数
  useEffect(() => {
    fetchData(pagination);
  }, []);


  // 定义了一个函数  handleTableChange
  const handleTableChange = (newPagination) => {
    fetchData(newPagination);
  };


  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <Table
      columns={columns}
      rowSelection={rowSelection}
      rowKey={(record) => record._id}
      dataSource={data}
      pagination={pagination}
      loading={loading}
      onChange={handleTableChange}
    />
  );
};

export default App;
